package cn.my;

import cn.hutool.core.util.ObjectUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @author Sun.Q
 * @since 九月, 30 2021
 */
public class MainFrame extends JFrame implements ClipboardOwner {

    Clipboard clipboard;  //剪贴板

    private JButton btnFile, btnImage, btnDelBefore;

    private JTextField stateText;

    private int uploading = 0;

    public MainFrame() {

        super("文件上传"); //调用父类构造函数

        clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); //获得系统剪贴板

        btnFile = new JButton("文件");
        btnFile.setBounds(30, 10, 100, 40);
        btnFile.addActionListener(new UploadFileListener()); //按钮事件处理

        btnImage = new JButton("图片");
        btnImage.setBounds(150, 10, 100, 40);
        btnImage.addActionListener(new UploadImageListener());

        stateText = new JTextField();
        stateText.setBounds(30, 60, 150, 30);

        btnDelBefore = new JButton("删除");
        btnDelBefore.setEnabled(false);
        btnDelBefore.addActionListener(new DeleteFilelistener());
        btnDelBefore.setBounds(190, 60, 60, 30);

        setLayout(null);

        add(btnFile);

        add(btnImage);

        add(stateText);

        add(btnDelBefore);

        setAlwaysOnTop(true);

        //add(panel);

        setSize(300, 150);

        Dimension scr = Toolkit.getDefaultToolkit().getScreenSize();
        int x = new Float((scr.getWidth() - this.getWidth())).intValue();
        int y = new Float((scr.getHeight() - this.getHeight())).intValue() - 50;
        setLocation(x, y);

        setVisible(true); //设置窗口为可视

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序

    }

    @Override
    public void lostOwnership(Clipboard clipboard, Transferable contents) {

    }

    /**
     * 上传文件按钮 监听器
     */
    class UploadFileListener implements ActionListener {

        public void actionPerformed(ActionEvent event) {

            Transferable contents = clipboard.getContents(this);
            try {
                if (preCheck(contents)) return;
                Object transferData = contents.getTransferData(DataFlavor.javaFileListFlavor);
                ArrayList<File> files = new ArrayList<>((Collection<? extends File>) transferData);
                uploading = 1;
                new Thread(() -> {
                    Result result = GitHub.upFile(files.get(0));
                    uploading = 0;
                    makeText(result);
                }).start();
                refreshState();
            } catch (UnsupportedFlavorException e) {
                e.printStackTrace();
                setText("剪切板中不是文件");
            } catch (IOException e) {
                e.printStackTrace();
                setText(e.getMessage());
            }
        }
    }


    /**
     * 上传图片按钮 监听器
     */
    class UploadImageListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            Transferable contents = clipboard.getContents(this);
            try {
                if (preCheck(contents)) return;
                if (!contents.isDataFlavorSupported(DataFlavor.imageFlavor)) return;
                BufferedImage bufferedImage = (BufferedImage) contents.getTransferData(DataFlavor.imageFlavor);
                uploading = 1;
                new Thread(() -> {
                    Result result = GitHub.upImg(bufferedImage);
                    uploading = 0;
                    makeText(result);
                }).start();
                refreshState();
            } catch (UnsupportedFlavorException e) {
                e.printStackTrace();
                setText("剪切板中不是图片流");
            } catch (IOException e) {
                e.printStackTrace();
                setText(e.getMessage());
            }
        }
    }

    class DeleteFilelistener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            if (stateText.getText().matches("^\\d{6}/.+\\..+$")) {
                setText(GitHub.delFile().getMsg());
                btnDelBefore.setEnabled(false);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        setText("");
                    }
                }).start();
            } else {
                JOptionPane.showMessageDialog(null, "格式错误");
            }
        }
    }


    private boolean preCheck(Transferable contents) {
        if (ObjectUtil.isNull(contents)) {
            setText("剪切板没有内容");
            return true;
        }
        if (contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            setText("剪切板中是文本");
            return true;
        }
        return false;
    }

    private void refreshState() {
        new Thread(() -> {
            while (uploading++ > 0) {
                uploading = uploading == 7 ? 1 : uploading;
                stateText.setText("上传中" + "。。。。。。".substring(7 - uploading));
                sleep();
            }
        }).start();
    }

    public static void sleep() {
        try {
            Thread.sleep(150);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void setText(String text) {
        stateText.setText(text);
    }

    public void makeText(Result result) {
        if (result.isSuccess()) {
            setText(result.getPath());
            clipboard.setContents(new StringSelection(result.getUrl()), MainFrame.this);
            btnDelBefore.setEnabled(true);
        } else {
            setText(result.getMsg());
            btnDelBefore.setEnabled(false);
        }
    }


}
